package org.raymond.iworks.study.performance.controller;

import lombok.extern.slf4j.Slf4j;
import org.raymond.iworks.apis.common.Result;
import org.raymond.iworks.repository.entity.TSysUser;
import org.raymond.iworks.repository.repository.TSysUserRepository;
import org.raymond.iworks.repository.utils.RandomUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Slf4j
@RestController("gcTestController")
@RequestMapping("/gc")
public class GCTestController {
    @Autowired
    TSysUserRepository tSysUserRepository;

    /**
     * jmeter
     * 线程组线程数: 4, 循环次数: 1000
     * 准确的吞吐量定时器: 目标吞吐量 1000/s, 批处理线程数: 3
     * -Xms80M -Xmx80M   采样数:4000,吞吐量为86.5, 平均:45,中位数:39,99百分位:124,95百分位:97,最大:797
     * -Xms300M -Xmx300M 采样数:4000,吞吐量为206.3,平均:17,中位数:18,99百分位:37, 95百分位:28,最大:73
     * @return
     */
    @GetMapping("/view")
    public Result viewGC(){
        log.info("gc view");
        TSysUser randUser = RandomUser.create("123456");
        //long start = System.nanoTime();
        // tSysUserRepository.save(randUser);
        // List<TSysUser> userList = tSysUserRepository.findAll();
        //long end = System.nanoTime();
        //System.out.println((end-start)/1000);
        return Result.success();
    }

    /**
     * jmeter
     * 线程组线程数: 4, 循环次数: 1000
     * 准确的吞吐量定时器: 目标吞吐量 1000/s, 批处理线程数: 3
     * -Xms80M -Xmx80M   采样数:4000,吞吐量为105.6,平均:36,中位数:29,99百分位:113,95百分位:96,最大:595
     * -Xms300M -Xmx300M 采样数:4000,吞吐量为200.4,平均:18,中位数:18,99百分位:32, 95百分位:28,最大:532
     * @return
     */
    @GetMapping("/view2")
    public Result viewGC2() throws ExecutionException, InterruptedException {
        TSysUser randUser = RandomUser.create("123456");
        //long start = System.nanoTime();
        CompletableFuture<List<TSysUser>> future = CompletableFuture.supplyAsync(()->tSysUserRepository.findAll());
        tSysUserRepository.save(randUser);
        List<TSysUser> userList = future.get();
        if(userList == null){
            userList = List.of(randUser);
        }else if(!userList.contains(randUser)){
            userList.add(randUser);
        }
        //long end = System.nanoTime();
        //System.out.println((end-start)/1000);
        return Result.success(userList);
    }
}
